﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using XuanJiSocket;
using System.Threading;

namespace ServerDemo
{
    class device
    {
        SocketHelper.TcpServer server;
        IPEndPoint ip;
        Thread thrd;
        List<byte> rcv_data = new List<byte>();
        Boolean new_data = false;

        public device(IPEndPoint ip, SocketHelper.TcpServer server)
        {
            this.ip = ip;
            this.server = server;
            thrd = new Thread(RCV_data);
            thrd.IsBackground = true;
            thrd.Start();
        }

        private void RCV_data()
        {
            int data_len = 0;
            int start_index = 0;
            while (true)
            {
                if (new_data)
                {
                    start_index = rcv_data.IndexOf(0xEB);
                    if (start_index > -1)
                    {
                        data_len = rcv_data[start_index + 1];
                        if (rcv_data[data_len - 1] == 0x85)
                        {
                            byte[] send_buf = new byte[2];
                            send_buf[0] = 0x33;
                            send_buf[1] = 0x44;
                            server.SendToClient(ip, send_buf);
                        }
                    }
                }
            }
        }

        public void RcvHandle(byte[] data, int len)
        {
            int i = 0;

            for (i = 0; i < len; i++)
            {
                rcv_data.Add(data[i]);
            }
        }
    }
}
